package com.thread.sync.sync03;

import java.util.ArrayList;
import java.util.List;

public class ListAdd02 {
    private volatile static List list = new ArrayList();

    public void addList() {
        list.add("houzheng");
    }

    public int getSize() {
        return list.size();
    }

    public static void main(String[] args) {
        final ListAdd02 list02 = new ListAdd02();
        final Object lock = new Object();
        //注意,一定要t2线程先启动,否则size直接达到10,线程会一直等待
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("t2启动..");
                    if (list02.getSize() != 5) {
                        try {
                            lock.wait();//线程等待,并释放锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("当前线程：" + Thread.currentThread().getName() + "收到通知线程停止..");
                    throw new RuntimeException();
                }
            }
        }, "t2").start();
        //t1,添加元素
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (lock) {
                        System.out.println("t1启动..");
                        for (int i = 0; i < 10; i++) {
                            list02.addList();
                            System.out.println(Thread.currentThread().getName() + " : " + list02.getSize());
                            Thread.sleep(500);
                            if (list02.getSize() == 5) {
                                System.out.println("已经发出通知..");
                                lock.notify();//发出通知,唤醒t2线程
                                //注意: notify方法不释放锁,如果此时不用wait方法,数组仍然会添加到10
                                lock.wait();//使用wait程序不会结束,一直等待,除非被唤醒继续执行
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();
    }
}
